3

I have two stateful widgets, the first one titled as MyApp which displays the list of employees in a ListView builder. The second stateful widget is titled ActionButton which is also a statefull widget.

The ActionButton widget returns an Alert Dialog. In the Alert Dialog I can add a new employee by entering the employee Name and Salary.

The issue is, in order to show the newly added employee I have to hot reload the application. Is there a way to inform MyApp widget that a new Employee has been added, and then display the new added employee in the ListView builder.

Below is the code for MyApp Widget:

                  import 'package:flutter/material.dart';

            import './database_helper.dart';
            import './floating_action_button.dart';

            void main() async {
              DatabaseHelper databaseHelper = new DatabaseHelper();
              List employees = [];
              employees = await databaseHelper.getAllEmployees();

              runApp(MyApp(employees));
            }

            class MyApp extends StatefulWidget {
              final List employees;

              MyApp(this.employees);

              @override
              _MyAppState createState() => _MyAppState();
            }

            class _MyAppState extends State<MyApp> {
              List employees = [];

              @override
              void initState() {
                super.initState();
                employees = widget.employees;
              }

              @override
              Widget build(BuildContext context) {
                return MaterialApp(
                  home: Scaffold(
                    appBar: AppBar(
                      title: Text("Employees"),
                    ),
                    body: Container(
                      child: ListView.builder(
                        itemCount: employees.length,
                        itemBuilder: (BuildContext context, int index) {
                          return new Card(
                            child: ListTile(
                              title: Text(employees[index]["empName"]),
                              subtitle: Text(
                                employees[index]["empSalary"].toString()),
                              trailing: RaisedButton(
                                onPressed: () {
                                  removeEmployee(
                                     employees[index]["id"], index);
                                },
                                child: Icon(
                                  Icons.remove,
                                  color: Colors.white,
                                ),
                                shape: CircleBorder(),
                                color: Theme.of(context).primaryColor,
                              ),
                            ),
                          );
                        },
                      ),
                    ),
                    floatingActionButton: ActionButton(),
                  ),
                );
              }

              Future<int> removeEmployee(int id, int index) async {
                DatabaseHelper databaseHelper = new DatabaseHelper();
                var result = await databaseHelper.deleteEmployee(id);
                if (result == 1) {
                  setState(() {
                    employees.removeAt(index);
                  });
                }
                return result;
              }
            }

Last but not least, ActionButton code:

    import 'package:employees/database_helper.dart';
    import 'package:employees/employee.dart';
    import 'package:flutter/material.dart';

    class ActionButton extends StatefulWidget {
      @override
      _ActionButtonState createState() => _ActionButtonState();
    }

    class _ActionButtonState extends State<ActionButton> {
      var _employeeNameController = new TextEditingController();
      var _employeeSalaryController = new TextEditingController();

      @override
      Widget build(BuildContext context) {
        return FloatingActionButton(
          child: Icon(
            Icons.add,
            color: Colors.white,
          ),
          onPressed: () {
            showDialog(
              context: context,
              builder: (_) {
                return AlertDialog(
                  title: Text("Add New Employees"),
                  content: Column(
                    children: <Widget>[
                      TextField(
                        controller: _employeeNameController,
                      ),
                      TextField(
                        controller: _employeeSalaryController,
                      ),
                    ],
                  ),
                  actions: <Widget>[
                    RaisedButton(
                      onPressed: () {
                        setState(
                          () {
                            addNewEmployee();
                          },
                        );
                      },
                      child: Text("Add Employee"),
                    ),
                  ],
                );
              },
            );
          },
        );
      }

      void addNewEmployee() async {
        DatabaseHelper databaseHelper = new DatabaseHelper();
        Employee employee = new Employee(
              _employeeNameController.text,
              int.parse(_employeeSalaryController.text));
        await databaseHelper.insertEmployee(employee);
      }
    }

Thank you for your help. Best Regards

1

1 Answer 1

1

Check this out. Flutter State Management

There are currently three ways to manage a state: SetState(), InheritedWidget and BLoC.

From my experience, if you what you want is a widget redraw, BLoC is the best. It's the most straightforward method.

Defining the BLoC and Provider:

import 'package:flutter/material.dart';
import 'dart:async';
import 'package:rxdart/rxdart.dart';

class EmployeeProvider extends InheritedWidget {
  final employeeBloc=EmployeeBloc();
  EmployeeProvider({Key key, @required Widget child,})
      : assert(child != null),
        super(key: key, child: child);

  static EmployeeBloc of(BuildContext context) {
    return (context.inheritFromWidgetOfExactType(EmployeeProvider) as EmployeeProvider).employeeBloc;
  }

  @override
  bool updateShouldNotify(EmployeeProvider old)=>true;
}

class EmployeeBloc{
  //This is the output interface of Bloc
  ValueObservable<List<Employee>> get list => _list.stream;//seedValue: '/'
  final _list = BehaviorSubject<List<Employee>>();//seedValue: '/'

  // This is the input interface of Bloc
  Sink<List<Employee>> get listChange => _listChangeController.sink;
  final _listChangeController = StreamController<List<Employee>>();

  EmployeeBloc(){
    _listChangeController.stream.listen(_handleListChange);
  }
  // This is the logic handling input
  void _handleListChange(List<Employee> newList){
    _list.add(newList);
  }
}

Usage:

  1. Wrap the entire app (or interested part) in a EmployeeProvider
  2. Whenever need to update the list

    EmployeeProvider.of(context).listChange.add(NewEmployeeList);
    
  3. Wrap the widget that needs to be redrawn in a StreamBuilder

    StreamBuilder<List<Employee>>( stream: EmployeeProvider.of(context).list, builder: (context, snapshot)=>ListView( children: snapshot.data.map(mapDataToListTile), ), );

Whenever the stream received a new value, the widget inside the StreamBuilder immediately redraws.

1
  • need to close the controller. Nov 20, 2018 at 14:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.