Home > Software engineering >  Flutter, How to access function in different stateful widget class
Flutter, How to access function in different stateful widget class

Time:05-20

I have a widget in a different stateful widget class and I wanna use it in a different class in a different file. How to access the widget.

stateful widget class

class List extends StatefulWidget {
  const List({Key? key}) : super(key: key);

  @override
  State<List> createState() => _ListState();
}

class _ListState extends State<List> {
  listCard(String name) {
    return Container();
  }

  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

I would to access listCard in

class BorrowersListProvider extends ChangeNotifier {
  List<Widget> borrowerList = [];

  addBorrower(String newBorrowerName) {
    borrowerList.insert(0, listCard(newBorrowerName));
    notifyListeners();
  }
}

CodePudding user response:

You have to just wrap your Contaniner with ChangeNotifierProvider like this.

ChangeNotifierProvider(
  create: (_) => Container(),
  child: MyApp(),
),

You can check here.

CodePudding user response:

Personally I order things like this:

As I will probably use more than one provider I create an appProvider file and this is the content (but you can do as Furkan Abbasioglu said in their answer, it's valid :D ):

List<SingleChildWidget> appProviders = [
  ChangeNotifierProvider<BorrowersListProvider>(create:(_) => BorrowersListProvider()),
];

You can add more in the [], separated by commas.

Then your provider seems good:

class BorrowersListProvider extends ChangeNotifier {
  List<Widget> borrowerList = [];

  addBorrower(String newBorrowerName) {
    borrowerList.insert(0, listCard(newBorrowerName));
    notifyListeners();
  }
}

So, your main should be something like this:

import 'package:flutter/material.dart';
import 'package:provider/provider.dart'

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: appProviders,
      child : MaterialApp(
      title: 'Material App',
      home: Scaffold(
        body: Center(
            child: Text('Hello World'),
        ),
      ),
    ),
    );
  }
}

and last, you can use the provider in this way in your widget (There's no need to use a stateful widget if you don't want, it's up to you):

context.read<BorrowersListProvider>().addBorrower(newBorrowerName);
  • Related