0

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

The argument type 'Box<dynamic>' can't be assigned to the parameter type 'ValueListenable<dynamic>'.

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

请在下面找到我的代码。

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')
                            ],
                          )],
                          ),
                        ]
                      )
                ),  
              );
          }
        );
      });
  }
}
4

1 回答 1

0

就像在 ListSession 小部件上一样添加.listenable()之后Hive.box('tasks')

于 2021-04-27T03:35:46.907 回答