如何使此lazyload滚动与提供程序一起使用

时间:2020-08-24 00:03:59

标签: flutter listview dart flutter-provider

大约需要7天的时间,才能为提供程序的lazyload listview创建一个有效的示例,并在实际示例中扑朔迷离,但仍然无法正常工作,因为我认为缺少某些东西

请注意:第一次加载,效果很好,当我滚动它时,它是打印(滚动)的,但是什么也没发生,它仍然在同一页面中 如果我尝试在 _onScrollUpdated 中返回 _todolist 变量,它将无法正确更改页面,并且在三遍之后我会看到此错误

E / flutter(7713):[错误:flutter / lib / ui / ui_dart_state.cc(166)] 未处理的异常:类型'String'不是类型的子类型 '列表'E / flutter(7713):#0 TodoService.fetchTodos (package:flutter_todo_provider / services / todo_service.dart:32:21)

json示例 https://jsonformatter.org/52c83e

todos_screen.dart

import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_todo_provider/helpers/http_exception.dart';

import 'package:provider/provider.dart';
import 'package:flutter_todo_provider/.env.dart';
import 'package:flutter_todo_provider/services/todo_service.dart';

class TodosScreen extends StatefulWidget {
  @override
  _TodosScreenState createState() => _TodosScreenState();
}

class _TodosScreenState extends State<TodosScreen> {
  ScrollController _controller;
  List<dynamic> _todoList;
  bool _isLoading ;
  @override
  void initState() {
    super.initState();
    _controller = ScrollController();
    _controller.addListener(_onScrollUpdated);
  }
  void dispose() {
    _controller.dispose();
    super.dispose();
  }
  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        title: Text(Configuration.AppName),
      ),
      body: FutureBuilder(
          future: _fetchListItems(),
          builder: (context, snapshot){
            if(snapshot.hasData){
              return _listItems(snapshot.data);
            }
            return _buildProgressIndicator();
          }
      ),
    );
  }
  _fetchListItems() async {
    try {
      await Provider.of<TodoService>(context, listen: false).loadNextPage();
      _todoList = Provider.of<TodoService>(context, listen: false).items;
    } on HttpException catch (e) {
      EasyLoading.showError(e.message);
    }
    return  _todoList ;

  }


  Widget _listItems(data){
    _isLoading =  Provider.of<TodoService>(context, listen: false).isLoading ;
    return ListView.builder(
      controller: _controller,
      itemCount: data.length  ,
      itemBuilder: (context, index) {
        return ListTile(
          title: Text(data[index].title),
          subtitle:Text(data[index].content),
          trailing: Icon(Icons.print),
        );
      },
    );
  }

  Future<void> _onScrollUpdated() async {
    print("Scroll11");
    var maxScroll = _controller.position.maxScrollExtent;
    var currentPosition = _controller.position.pixels;
    if (currentPosition == maxScroll ) {
      try {
        await Provider.of<TodoService>(context, listen: false).loadNextPage();
        _todoList = Provider.of<TodoService>(context, listen: false).items;

//返回_todoList;如果使用此行,我会看到错误

      } on HttpException catch (e) {
        EasyLoading.showError(e.message);
      }
    }
  }

  Widget _buildProgressIndicator() {
    _isLoading =  Provider.of<TodoService>(context, listen: false).isLoading ;
    return new Padding(
      padding: const EdgeInsets.all(8.0),
      child: new Center(
        child: new Opacity(
          opacity: _isLoading ? 1.0 : 00,
          child: new CircularProgressIndicator(),
        ),
      ),
    );
  }
}

todo_service.dart

 import 'dart:io';
    import 'package:dio/dio.dart';
    import 'package:flutter/foundation.dart';
    import 'package:flutter_todo_provider/.env.dart';
    import 'package:flutter_todo_provider/models/todo.dart';
    
    class TodoService with ChangeNotifier {
      bool isLoading = false;
      bool isFetching = false;
      int currentPage = 1;
      int totalRows = 10;
      List<Todo> items = [];
    
    
      loadNextPage() async {
        await fetchTodos(currentPage);
        currentPage++;
        notifyListeners();
      }
    
      Future fetchTodos(int currentPage) async {
    
        try {
          //404
          var options = Options(headers: {
            HttpHeaders.authorizationHeader: 'Basic ${Configuration.authToken}'
          });
          Map<String, dynamic> qParams = {
            'current_page': currentPage,
          };
          Response  response = await Dio().get('${Configuration.ApiUrl}/todos/my_todos',   options: options, queryParameters: qParams);
          List<dynamic> responseBode =  response.data["data"];
          responseBode.forEach(( dynamic json) {
            items.add(Todo.fromJson(json));
          });
          notifyListeners();
    
        } on DioError catch (e) {
          print("Error Message" + e.response.statusMessage);
          return items=[];
        }
    
    
      }
    

}

1 个答案:

答案 0 :(得分:0)

代码如下:

class TodoScreen extends StatefulWidget {
  // Your service goes here
  // (the class extending ChangeNotifier)
  @override
  _TodoScreenState createState() => _TodoScreenState();
}

class _TodoScreenState extends State<TodoScreen> {
  final TodoService todoService = TodoService();

  ScrollController _controller;

  @override
  void initState() {
    super.initState();
    _controller = ScrollController();
    _controller.addListener(_onScrollUpdated);
    loadNextPage();
  }

  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Configuration.AppName'),
      ),
      body: ChangeNotifierProvider.value(
        value: todoService,
        child: Consumer<TodoService>(builder: (_, ctl, __) {
          if (todoService.isLoading) {
            return _buildProgressIndicator();
          } else {
            return _listItems(todoService.items);
          }
        }),
      ),
    );
  }

  Widget _listItems(data) {
    return ListView.builder(
      controller: _controller,
      itemCount: data.length,
      itemBuilder: (context, index) {
        return ListTile(
          title: Text(data[index].title),
          subtitle: Text(data[index].content),
          trailing: Icon(Icons.print),
        );
      },
    );
  }

  Widget _buildProgressIndicator() {
    return new Padding(
      padding: const EdgeInsets.all(8.0),
      child: new Center(
        child: CircularProgressIndicator(),
      ),
    );
  }

  Future<void> _onScrollUpdated() async {
    var maxScroll = _controller.position.maxScrollExtent;
    var currentPosition = _controller.position.pixels;
    if (currentPosition == maxScroll) {
      todoService.loadNextPage();
    }
  }
}

请注意,我没有更改您的服务。 notifyListeners将为我们完成所有工作。

使用Provider时,其想法是将所有数据保留在控制器或服务(扩展ChangeNitifier的类)中,并且仅将变量与notifyListeners一起使用即可更改屏幕的行为。

屏幕需要侦听更改,为此,我们将ChangeNotifierProvider.value与Consumer(builder:(_,ctl,__){})对使用。 在小部件树的较高级别中使用ChangeNotifierProvider,并在需要更新小部件的地方使用Consumer 。您甚至可以使用多个Consumer,它们都只需要位于ChangeNotifierProvider下即可。