首页 > 解决方案 > Flutter:onRefresh 回调返回 null

问题描述

对不起,我是新来的颤振并试图学习它。我有一个问题RefreshIndicator

当我尝试拉它时,出现如下错误:

════════ Exception caught by material library ══════════════════════════════════════════════════════
The following assertion was thrown when calling onRefresh:
The onRefresh callback returned null.

The RefreshIndicator onRefresh callback must return a Future.
════════════════════════════════════════════════════════════════════════════════════════════════════

目前我正在使用flutter_bloc。这是我的示例代码

TableList_bloc.dart

import 'dart:async';
import 'package:bloc/bloc.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:pos_project_bloc/modal/api.dart';

class ModalTableList {
  final String Table_Number;
  final String Name_Table;

  ModalTableList(
      this.Table_Number,
      this.Name_Table,
      );
}

class tablelistbloc extends Bloc<bool, List<ModalTableList>>{
  @override
  // TODO: implement initialState
  List<ModalTableList> get initialState => [];

  @override
  Stream<List<ModalTableList>> mapEventToState(bool event) async* {
    // TODO: implement mapEventToState

    List<ModalTableList> tablelist =[];
    try {

      final response = await http.get(BaseUrl.GetTableList);
      final data = jsonDecode(response.body);
      if (data.length != 0) {
        data.forEach((api) {
          tablelist.add(
              ModalTableList(
                api['Table_Number'],
                api['Name_Table'],
              )
          );
          print("test"+api['Table_Number'].toString());
        });
        print("Get Table List : sukses");
      } else {
        print('data kosong');
      }
    } catch (e) {
      print("Error GetTableList :");
      print(e);
    }

    yield tablelist;
  }
}

TabeList.dart

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:pos_project_bloc/bloc/TableList_bloc.dart';
import 'package:pos_project_bloc/modal/SharedPreferences.dart';

class TableList extends StatefulWidget {
  @override
  _TableListState createState() => _TableListState();

}

class _TableListState extends State<TableList> {
  @override

  void initState() {
    super.initState();
    BlocProvider.of<tablelistbloc>(context).add(true);
  }

  Widget build(BuildContext context) {

    final GlobalKey<RefreshIndicatorState> refresh = GlobalKey<RefreshIndicatorState>();

    Future<Null> _refresh() async{
      BlocProvider.of<tablelistbloc>(context).add(true);
    }

    return Scaffold(
        appBar: AppBar(
            backgroundColor: Colors.lightBlueAccent,
            title: new Center(
              child: new Text('Available Table',
                  style: new TextStyle(color: Colors.white, fontSize: 15.0)),
            )
        ),
      floatingActionButton: Container(

        child: Column(
          mainAxisAlignment: MainAxisAlignment.end,
          children: <Widget>[

            Padding(
              padding: EdgeInsets.all(5.0),
              child: FloatingActionButton.extended(
                heroTag: 1,
                icon: Icon(Icons.refresh),
                label: Text('Refresh Table List'),
                onPressed: () {
                  BlocProvider.of<tablelistbloc>(context).add(true);
                },
              ),
            )
          ],
        ),
      ),

      body: RefreshIndicator(
        onRefresh: (){
          _refresh();
        },
        key: refresh,
        child: BlocBuilder<tablelistbloc,List<ModalTableList>>(

          builder: (context,tablelist)=> ListView.builder(
            itemCount: tablelist.length,
            itemBuilder: (context,index){

              final x = tablelist[index];
              return GestureDetector(
                onTap: (){
                  print("Selected Available Table On Tap : " + x.Table_Number);

                  Shared_Preferences().SaveTableNumber(
                      x.Table_Number
                  );

                  Navigator.pushReplacementNamed(context, '/POS');
                },
                child: Container(
                  decoration: BoxDecoration(
                      border: Border(
                          bottom: BorderSide(
                            width: 2.0,
                            color: Colors.grey.withOpacity(0.4),
                          ))),
                  padding: EdgeInsets.all(10.0),
                  child: Row(
                    children: <Widget>[
                      Icon(
                        Icons.table_chart,
                        size: 100.0,
                        color: Colors.lightBlueAccent,
                      ),
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Text(
                            'Table Number :  ' + x.Table_Number,
                            style: TextStyle(
                                fontSize: 20.0,
                                fontWeight: FontWeight.bold,
                                color: Colors.lightBlueAccent),
                          ),

                          Text(
                            'Name :  ' + x.Name_Table,
                            style: TextStyle(
                                fontSize: 20.0,
                                fontWeight: FontWeight.bold,
                                color: Colors.lightBlueAccent),
                          ),
                        ],
                      )
                    ],
                  ),
                ),
              );
            },
          ),
        ),
      )
    );
  }
}

标签: flutter

解决方案


只需添加异步。

  onRefresh: () async {
    GetTableList.add(true);
  },

onRefreshRefreshCallback, RefreshCallback 是 Future Function()。

所以如果GetTableList.add(true) 不返回Future,必须添加async。


推荐阅读