Home > Blockchain >  In Flutter, is there a way in which I can draw different contents and dynamic lists from the stored
In Flutter, is there a way in which I can draw different contents and dynamic lists from the stored

Time:12-01

To solve the first problem, the method I'm currently using is to put a content variable in the body while loading the file async and when the loading is done, call setState() and set the value of content.

class _MyHomePageState extends State<MyHomePage>{
  dynamic content;
  void setContent(bool? hasRes){
    setState(() {
      if(hasRes!=null&&hasRes){
        content = const ContentWhenHasRes();
      }else{
        content = const ContentWhenNoRes();
      }
    });
  }
  @override
  Widget build(BuildContext context){
    //Load the $hasRes$ var and determine which interface to draw
    SharedPreferences.getInstance().then((pref) => {
      setContent(pref.getBool('hasRes'))
    });
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: content
    );
  }
}

But I don't know whether this works and is there a more elegant way to do this? Also, I'm finding it problematic to load a list from local storage to show in ListView. I know to use `ListView.builder' however, my problem is still with the i/o part.

CodePudding user response:

another approach is setState() the hasRes variable:

class _MyHomePageState extends State<MyHomePage>{
  bool _hasRes = false;

  @override
  void initState() {
    super.initState();
    //Do this in initState()
    SharedPreferences.getInstance().then((pref) => {
      _hasRes = pref.getBool('hasRes');
      setState((){});
    });
  }

  @override
  Widget build(BuildContext context){
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: _hasRes ? ContentWhenHasRes() : ContentWhenNoRes(),
    );
  }
}

CodePudding user response:

SharedPreferences.getInstance().then((pref) => {
  setContent(pref.getBool('hasRes'))
});

These code should not place in build() method, because build() method is execute frequently, place the io code in initState() instead.

  • Related