简体   繁体   中英

I Want to Add Widgets Dynamically with Provider

I'm using Provider package, and I want to dynamically add widgets to display. I wrote the code like below, but the widgets doesn't show anything. No errors have occurred.

// Contains widget and related data
class WidgetData {
    Widget? child;  // want to show this
    String data1;
    int data2;
}    

class Model exteds ChangeNotifier {
    List<WidgetData> widget;   // I want to show all of this widget.child
    
    void addWidget(Widget child) {
        print("Called1") // "Called1"
        var w = widgets.toList();
        w.add(child);
        widgetData = w;
        notifyListeners();
    }
}

class Example extends StatelessWidget {
    @override
    build (BuildContext context) {
        return Scaffold(
            body: Column(children: [
                 for(var i in context.watch<Model>().widget) i.child!;
        ]);
    }
}

When the button pushed, context.read<Model>().addWidget(Text("test")) will be called. But still doesn't show widgets.

 // inside of build(BuildContext context)
 FloatingActionButton(
   onPressed: () => context.read<Model>().addWidget(Text("test")),
   child: Icon(Icons.abc)
 ); 

Of course I built the tree of provider in main .

void main() {
  runApp(MultiProvider(
     ChangeNotifierProvider<Model>(
       create: (_) => Model()),
  ));

  child: 
  ....
}

It is discouraged to create and store Widgets outside of the build function in Flutter. Your provider should not provide Widgets, but the data needed to construct widgets, and you then construct the widgets inside the build method.

For example, if instead of a list of Widgets you had a list of Strings, then in the build method you convert that list of Strings easily into Text widgets like this: Column(children: stringlist.map((e) => Text(e)).toList())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM