出现错误:不能将 Box<dynamic>' 分配给参数类型 'ValueListenable<dynamic>'

Posted

技术标签:

【中文标题】出现错误:不能将 Box<dynamic>\' 分配给参数类型 \'ValueListenable<dynamic>\'【英文标题】:Getting error: Box<dynamic>' can't be assigned to the parameter type 'ValueListenable<dynamic>'出现错误:不能将 Box<dynamic>' 分配给参数类型 'ValueListenable<dynamic>' 【发布时间】:2021-07-19 13:16:33 【问题描述】:

我是 Flutter 的新手,我使用 Hive 作为我的数据库。我正在尝试使用 ValueListenableBuilder 小部件来收听新的数据库更新。但我收到以下错误。

The argument type 'Box&lt;dynamic&gt;' can't be assigned to the parameter type 'ValueListenable&lt;dynamic&gt;'.

但是我在list_session Widget 上使用了相同的代码,但我没有遇到任何错误。但是,对于第二个小部件,我遇到了这个错误。我正在粘贴代码以供参考。

请在下面找到我的代码。

main.dart file

import 'package:flutter/material.dart';
import 'package:hive/hive.dart';
import 'package:path_provider/path_provider.dart' as path_provider;
import 'package:time_tracker/models/sessions.dart';
import 'pages/home.dart';
import 'pages/create_session_form.dart';

void main() async 
  WidgetsFlutterBinding.ensureInitialized();
  // Inititalise Hive DB
  final appDocumentDirectory = await path_provider.getApplicationDocumentsDirectory();
  Hive.init(appDocumentDirectory.path);
  Hive.registerAdapter(SessionAdapter());

  await Hive.openBox('tasks');
  await Hive.openBox('tags');
  Color themeColor = Colors.purple;
  runApp(MaterialApp(
    // home: Home(),
    initialRoute: '/',
    routes: 
      '/': (context) => FutureBuilder(
        future: Hive.openBox('sessions'),
        builder: (BuildContext context, AsyncSnapshot snapshot) 
          if(snapshot.connectionState == ConnectionState.done) 
              return Home();
           else 
            return Scaffold();
          
        
      ),
      '/create_session': (context) => CreateSessionForm(themeColor: themeColor)
    ,
  ));


create_session_form.dart file

import 'package:flutter/material.dart';
import 'package:hive/hive.dart';
import 'package:time_tracker/models/sessions.dart';
import 'package:time_tracker/models/tags.dart';
import 'package:time_tracker/models/tasks.dart';
import 'package:time_tracker/my_widgets/dropdown_widget.dart';

class CreateSessionForm extends StatefulWidget 
  final Color themeColor;
  final DateTime activeDate;
  final Function changeDate;
  CreateSessionForm (Key key, this.themeColor, this.activeDate, this.changeDate) : super(key: key);
  @override
  CreateSessionFormState createState() => CreateSessionFormState(themeColor: this.themeColor, activeDate: this.activeDate, changeDate: this.changeDate);


class CreateSessionFormState extends State<CreateSessionForm> 

  final _formKey = GlobalKey<FormState>();
  Color themeColor;
  DateTime activeDate;
  final Function changeDate;
  CreateSessionFormState(this.themeColor, this.activeDate, this.changeDate);
  String taskName;
  String tagName;
  List<String> taskNames = [];
  // List<String> tagNames = [];
  String sessionDescription;
  Map<String, Color> sessionTags = ;
  DateTime startTime;
  DateTime endTime;
  bool isTaskAdded = false;
  bool isTagAdded = false;
  Color color;
  TimeOfDay _startTime;
  TimeOfDay _endTime;

  Map<String, Color> colors = 
    'Amber': Colors.amber,
    'Blue': Colors.blue,
    'Black': Colors.black,
    'Orange': Colors.orange,
    'Pink': Colors.pink,
    'Red': Colors.red,
    'Yellow': Colors.yellow
  ;


  void addSession(Session session) 
    Hive.box('sessions').add(session);
  

  @override
  Widget build(BuildContext context) 
    // Hive.openBox('tasks');
    // dynamic tasksBox = Hive.box('tasks');
    return Scaffold(
      appBar: AppBar(
        title: Text('Create Session'), 
        backgroundColor: this.themeColor,
      ),
      body: Padding(
        padding: EdgeInsets.all(10.0),
        child: Form(
          key: _formKey,
          child: Column(
            children: <Widget>[
              ValueListenableBuilder(
                valueListenable: Hive.box('tasks'),
                builder: (context, tasksBox, widget) 
                  return MyDropDownWidget(taskName, taskNames, changeTask);
                ,
              ),
            ],
          ),
        ),
      )
    );
  

list_sessions - This widget works perfectly without issues
import 'package:flutter/material.dart';
import 'package:hive/hive.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:time_tracker/models/sessions.dart';


class ListSessions extends StatelessWidget 
  ListSessions(this.activeDate);
  final activeDate;
  
  @override
  Widget build(BuildContext context) 

    return ValueListenableBuilder(
      valueListenable: Hive.box('sessions').listenable(), 
      builder: (context, sessionsBox, widget) 
        DateTime greaterDate = activeDate.add(const Duration(days: 1));
        return ListView.builder(
          itemCount: sessionsBox.length,
          itemBuilder: (context, index) 
            final sessions = sessionsBox.getAt(index) as Session;
              return Card(
                child: Padding(
                  padding: EdgeInsets.fromLTRB(10.0, 5, 10.0, 5),
                  child: Column(
                    children: <Widget>[
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: <Widget>[
                          Text(
                            // 'Create Flutter App',
                            sessions.taskName,
                            style: TextStyle(
                              fontSize: 18.0,
                              fontWeight: FontWeight.w600
                            ),
                          ),
                          
                        ]
                      ),
                      SizedBox(height: 20.0),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: <Widget>[
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: sessions.sessionTags.entries.map((entry) 
                              // var w = Text(entry.value);
                              // doSomething(entry.key);
                              return Row(
                                    children: [
                                      Icon(Icons.circle, color: entry.value, size: 18.0),
                                      SizedBox(width: 5.0),
                                      Text(entry.key)
                                    ]
                                  );
                            ).toList()),
                            
                            
                          Column(
                            children: <Widget>[
                              IconButton(
                                icon: Icon(Icons.delete), 
                                onPressed: () 
                                  // Hive.box('sessions').deleteAt(index);
                                  Hive.box('sessions').deleteAt(index);
                                
                              ),
                              SizedBox(height: 5.0),
                              Text('Completed')
                            ],
                          )],
                          ),
                        ]
                      )
                ),  
              );
          
        );
      );
  

【问题讨论】:

【参考方案1】:

只需在Hive.box('tasks') 之后添加.listenable(),就像您在 ListSession 小部件上所做的那样

【讨论】:

以上是关于出现错误:不能将 Box<dynamic>' 分配给参数类型 'ValueListenable<dynamic>'的主要内容,如果未能解决你的问题,请参考以下文章

出现“List<dynamic>”类型的错误不是“Map<String, dynamic>”类型的子类型

类型 'List<dynamic>' 不是类型 'Map<String, dynamic>' 的子类型在颤振应用程序中出现此错误

Flutter 错误:期望一个类型为“Map<String, dynamic>”的值,但出现了一个类型为“List<dynamic>”的值

颤振错误:参数类型“列表<动态>?”不能分配给参数类型“列表<动态>”

参数类型“User”不能分配给参数类型“Future<dynamic>”。? [复制]

Vagrant 1.8.7 不能下载box的bug