Provider: trigger setState inside another widget

Viewed 16

Hello i need help with my Provider that should trigger changes. I am using Provider for my State management. Ill inserted the Provider as followed:

main.dart

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(
          create: (_) => ThemeProvider()..initialize(),
        ),
        ChangeNotifierProvider(
          create: (_) => HeadingProvider(),
        ),
      ],
      child: const Master(),
    );
  }
}

My Provider looks like this:

class HeadingProvider extends ChangeNotifier {
  List<Widget> myWidgetList = [
    const Text("hello"),
  ];

  addHeading() {
    myWidgetList.add(const Text("hello 2"));
    notifyListeners();
  }
}

I now have two different Widgets, one that triggers the function addHeading() and one that shows the list of the Provider. When I now call the function addHeading() the element Text("hello 2") gets created but does not trigger show in the UI. I have to manually hotreload to see changes.

Provider is referred like this in the two widgets

final headingController = Provider.of<HeadingProvider>(context);

Widget that triggers the function.

    DragItemWidget(
      onTap: () {
        headingController.addHeading();
      },

Widget that displayes the list.

Container(
 width: 390,
 height: 300,
 child: ListView(
   children: headingController.myWidgetList 
 ),
),

Can you help me how I can see the added element in the UI immediately? (Maybe I have to trigger setState ?)

1 Answers

Wrap you ListView into a Consumer so that it will be rebuilt when you call notifyListeners():

Container(
 width: 390,
 height: 300,
 child: Consumer<HeadingProvider>(builder: (context, headingProvider, _) {
   return ListView(
     children: headingProvider.myWidgetList 
   );
 }),
),
Related