gpt4 book ai didi

flutter - 重新加载时,我应该如何更新无状态小部件?

转载 作者:行者123 更新时间:2023-12-03 02:54:59 24 4
gpt4 key购买 nike

我正在使用 JSON 文件来存储我想要显示和更新的列表。我有一个 StatefulWidget(称为“HOME”),它使用 ListView.builder 显示列表。我还有一个 StatefulWidget(称为“ADD”),它向列表中添加一个对象并更新 JSON 文件。当我完成添加列表导航回“主页”时,我收到此错误:
Error Upon Returning to HOME
enter image description here

家:

class Home extends StatefulWidget {
@override
_HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {

PlayerList playerList;



@override
void initState() {
super.initState();
readPlayerData().then((PlayerList list) {
playerList = list;
});


}

@override
Widget build(BuildContext context) {

// add Player to the PlayerList
void addPlayer() async {
await Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (context) => AddPlayer()),
);

initState();
}

void removePlayer(int index) async {

playerList.players.removeAt(index);
await writePlayerData(playerList);
}

playerList = ModalRoute.of(context).settings.arguments;

return Scaffold(
backgroundColor: Colors.grey[900],
appBar: AppBar(
title: Text('Smash Tracker'),
centerTitle: true,
backgroundColor: Colors.grey[850],
elevation: 0,
),
floatingActionButton: FloatingActionButton(
onPressed: () async {addPlayer();},
child: Icon(Icons.add),
backgroundColor: Colors.grey[600],
),
body: Padding(
padding: EdgeInsets.all(15.0),
child: Container(
child: Card(
color: Colors.grey[900],
shadowColor: Colors.black87,
child: ListView.builder(
itemCount: playerList.players.length,
itemBuilder: (context, index) {
return ListTile(
//leading: characterIcons(playerList.players[index]),
title: Text(
playerList.players[index].playerId,
style: TextStyle(
color: Colors.amberAccent,
),
),
subtitle: Text(
playerList.players[index].playerSetCount,
style: TextStyle(
color: Colors.amberAccent,
),
),
onTap: () {
Navigator.pushNamed(context, '/playerCard', arguments: {
'player': playerList.players[index],
'playerList': playerList,
'index': index
});
},
trailing: IconButton(
onPressed: () async {
removePlayer(index);
PlayerList newPlayerList = await readPlayerData();
setState(() {
playerList = newPlayerList;
});
},
icon: Icon(Icons.delete_outline),
color: Colors.white,
),
);
},
),
),
),
),
);
}

}
按下“保存”按钮时用于保存新对象的代码
添加:
  void _saveForm() async {

PlayerList playerList = await readPlayerData();

Player newPlayer = new Player("${playerName.trim()}", "0 - 0",
new Characters(_myChar1Result, _myChar2Result), "");
playerList.players.add(newPlayer);

await writePlayerData(playerList);

Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (context) => Home()),
);
}
我认为当 ListView.builder 尝试调用 playerList 对象时会发生错误。我不知道。我很乐意提供任何其他信息。

'编辑:'这是 readPlayerData() 包括它依赖的方法:
Future<PlayerList> readPlayerData () async {
try {
final file = await _localFile;
String contents = await file.readAsString();
final jsonResponse = (jsonDecode(contents)); //wrap in encode
PlayerList playerList = PlayerList.fromJson(jsonResponse);
return playerList;
} catch (e) {
print(e);
return getPlayerList(); //just loads a placeholder json in the assets folder;
}

Future<String> get _localPath async {
final directory = await getApplicationDocumentsDirectory();
return directory.path;
}

Future<File> get _localFile async {
final path = await _localPath;
print(path);
return File('$path/playerData.json');
}
json 文件以我想要的方式保存。

最佳答案

您的代码中存在多个问题,这就是我修复它的方式。
解决方案 我会明智地为您提供解决方案文件,因此请继续
1. 首页

  • 移出方法 => addPlayer()removePlayer()
  • 添加 setState((){})playerListinitState()
  • 完全删除此行,playerList = ModalRoute.of(context).settings.arguments; .用于此行的错误太多
  • Navigator.pushAndRemoveUntil()的正确使用在 addPlayer()
  • class _HomeState extends State<Home> {
    PlayerList playerList;

    @override
    void initState() {
    super.initState();
    readPlayerData().then((PlayerList list) {
    setState(() => playerList = list);
    });
    }

    // add Player to the PlayerList
    void addPlayer() async {
    Navigator.pushAndRemoveUntil(
    context,
    MaterialPageRoute(builder: (context) => AddPlayer()),
    (_) => false);

    //initState();
    }

    void removePlayer(int index) async {
    playerList.players.removeAt(index);
    await writePlayerData(playerList);
    }

    @override
    Widget build(BuildContext context) {
    // copy paste your Scaffold content here
    // rest everything will be same
    // NO layerList = ModalRoute.of(context).settings.arguments;
    return Scaffold();
    }
    }
    2. 添加
  • 字符模态的导入是错误的,并且是相互冲突的。它应该像 import 'package:smash_tracker/models/character_model.dart' as Characters; 一样导入
  • 然后在传递对象时,应该像这样传递 new Characters.Characters(_myChar1Result, _myChar2Result)
  • Navigator.pushAndReplaceUntil()的正确用法
  • 删除小部件内的这一行{} PlayerList playerList = ModalRoute.of(context).settings.arguments;
  • 其余的都是一样的
  • import 'package:smash_tracker/models/character_model.dart' as Characters;

    void _saveForm() async {
    setState(() {
    _myChar1Result = _myChar1;
    _myChar2Result = _myChar2;
    });

    PlayerList playerList = await readPlayerData();

    Player newPlayer = new Player("${playerName.trim()}", "0 - 0",
    new Characters.Characters(_myChar1Result, _myChar2Result), "");
    playerList.players.add(newPlayer);

    print('added new Player');
    await writePlayerData(playerList);
    print('updated JSON');

    Navigator.pushAndRemoveUntil(
    context,
    MaterialPageRoute(builder: (context) => Home())
    (_) => false);
    }

    @override
    Widget build(BuildContext context) {
    // no more PlayerList playerList = ModalRoute.of(context).settings.arguments;
    return Scaffold();
    }
    测试应用程序后,它的工作原理如下。
    Result GIF

    关于flutter - 重新加载时,我应该如何更新无状态小部件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63092152/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com