Dat Minh
Dat Minh

Reputation: 55

How can I pass bloc to another screen in flutter

in main.dart

    void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Quản lý món ăn',
      home: BlocProvider(
        create: (context) => MonAnBloc(MonAnRepository())..add(LoadMonAns()),
        child: MonAnListScreen(),
      ),
    );
  }
}

then in the MonAnListScreen I have a floating action button

class MonAnListScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Danh sách món ăn')),
      body: BlocBuilder<MonAnBloc, MonAnState>(
        builder: (context, state) {
          if (state is MonAnLoading) {
            return const Center(child: CircularProgressIndicator());
          } else if (state is MonAnsLoaded) {
              ...
          } else if (state is MonAnError) {
            return Center(child: Text('Lỗi: ${state.message}'));
          } else {
            return const Center(child: Text('Chưa có dữ liệu'));
          }
        },
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => MonAnFormScreen(),
            ),
          );
        },
        child: const Icon(Icons.add),
      ),
    );
  }
}

Try to wrap the button or when Navigate with BLocProvider =.vlaue but in not working

MonAnForm.dart:

@override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.monAn == null ? 'Thêm món ăn' : 'Sửa món ăn'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Form(
          key: _formKey,
          child: Column(
            children: <Widget>[
              TextFormField(
                controller: _tenMonAnController,
                decoration: const InputDecoration(labelText: 'Tên món ăn'),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return 'Vui lòng nhập tên món ăn';
                  }
                  return null;
                },
              ),
              TextFormField(
                controller: _giaController,
                decoration: const InputDecoration(labelText: 'Giá'),
                keyboardType: TextInputType.number,
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return 'Vui lòng nhập giá';
                  }
                  if (double.tryParse(value) == null) {
                    return 'Giá phải là số';
                  }
                  return null;
                },
              ),
              ElevatedButton(
                onPressed: () {
                  if (_formKey.currentState!.validate()) {
                    final tenMonAn = _tenMonAnController.text;
                    final gia = double.parse(_giaController.text);

                    final monAnBloc =
                        context.read<MonAnBloc>(); // Truy cập bloc

                    if (widget.monAn == null) {
                      monAnBloc.add(AddMonAn(MonAn(
                          id: 0,
                          tenMonAn: tenMonAn,
                          gia: gia))); // Thêm món ăn mới
                    } else {
                      monAnBloc.add(UpdateMonAn(MonAn(
                          id: widget.monAn!.id,
                          tenMonAn: tenMonAn,
                          gia: gia))); // Sửa món ăn
                    }
                    Navigator.pop(context); // Quay lại màn hình danh sách
                  }
                },
                child: Text(widget.monAn == null ? 'Thêm' : 'Sửa'),
              ),
            ],
          ),
        ),
      ),
    );
  }

what can I do now to it can use bloc ? I dont get it alway return ProviderNotFoundException (Error: Could not find the correct Provider above this MonAnFormScreen Widget.

Upvotes: 0

Views: 31

Answers (1)

Munsif Ali
Munsif Ali

Reputation: 6131

Change your FloatingActionButton onPressed code and wrap the Widget with the to this to provide the provider down to the widget tree

floatingActionButton: FloatingActionButton(
        onPressed: () {
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (_) =>BlocProvider<MonAnBloc>(
                  builder: (_) => MonAnBloc(),
                 child: MonAnFormScreen(),
                ),
            ),
          );
        },
        child: const Icon(Icons.add),
      ),

above code is if you are using this Bloc only in that specific screen. if the bloc is not specific to that screen and you want to access it all over other screens as well then wrap the BlocProvider around your MaterialApp Widget.

Upvotes: 0

Related Questions