我试图将未来返回的值存储在列表中,但我一直收到一个空字符串作为回报。我正在从 SQLite 数据库中提取期货数据,所以我也必须显示这些功能。
我正在显示以下值的应用程序视图:
import 'dart:ui' as ui;
import '../../services/crud/main_services.dart';
import 'package:directed_graph/directed_graph.dart';
import 'package:flutter/material.dart';
import 'dart:developer' as devtools show log;
import 'dart:async';
class NewMapsView extends StatefulWidget {
const NewMapsView({super.key});
@override
State<NewMapsView> createState() => _NewMapsViewState();
}
class _NewMapsViewState extends State<NewMapsView> {
//DatabaseNodes? _initNode;
late final MainService _mainService;
//gets all data from database
Future<List<DatabaseNodesWeights>> getNodesWeightsAsList() async {
final nodes = await _mainService.getAllNodesWeights();
return nodes.toList();
}
//gets all data from database
Future<List<DatabaseNodes>> getNodesAsList() async {
final nodes = await _mainService.getAllNodes();
List<DatabaseNodes> asList = [];
for (int i = 0; i < nodes.length; ++i) {
asList = nodes.toList();
devtools.log(asList[i].toString());
}
return asList;
}
//#######################get the nodes somewhere around here############################
List<String> lightestPath = [];
//initialize comparator variable
int comparator(
String s1,
String s2,
) {
return s1.compareTo(s2);
}
//initialize sum variable
int sum(int left, int right) => left + right;
var graph = WeightedDirectedGraph<String, int>(
{},
summation: (int a, int b) => a + b,
zero: 0,
comparator: (String a, String b) => a.compareTo(b),
);
List<DatabaseNodesWeights> nodesWeights = [];
List<DatabaseNodes> nodesAllInfo = [];
//initializing
Future<List<String>> initializeGraph() async {
nodesWeights = await getNodesWeightsAsList();
for (int i = 0; i < nodesWeights.length; ++i) {
devtools.log(nodesWeights[i].node_1);
}
List<DatabaseNodes> nodesAllInfo = await getNodesAsList();
List<DatabaseNodesWeights> specificNodeConnections = [];
//make sure all the nodes have been extracted
for (int j = 0; j < nodesAllInfo.length; ++j) {
for (int i = 0; i < nodesWeights.length; ++i) {
nodesWeights[i].toString();
specificNodeConnections = await _mainService.getNodesWeightsUseNode(
theNodesName: nodesAllInfo[j].nodeName,
theNodesWeightId: nodesAllInfo[j].id);
graph.addEdge(
specificNodeConnections[i].node_1,
specificNodeConnections[i].node_2,
specificNodeConnections[i].weight);
}
}
//calculate List of path in between
List<String> listOfPointsInBetween = graph.lightestPath(
specificNodeConnections[0].node_1, specificNodeConnections[0].node_2);
return listOfPointsInBetween;
}
var attempt2 = [];
//override built-in function initState
@override
void initState() {
//open database
//initializeGraph();
_mainService = MainService();
String firstVertex = 'Physics Building';
devtools.log('$graph.vertexExists(FirstVertex)');
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('map route'),
),
body: FutureBuilder(
future: initializeGraph(),
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.done:
lightestPath = snapshot.data as List<String>;
return Stack(
children: <Widget>[
Text(
'\nLightest path a -> $lightestPath , weight: ${graph.weightAlong(lightestPath)}'),
Text(nodesWeights.toString()),
],
);
default:
return const CircularProgressIndicator();
}
}),
);
}
}
我如何从数据库中提取数据到 dart 的文件中使用的函数:
//This file translates database data into actual dart language that can be implemented
import 'dart:async';
//import 'dart:html';
import 'dart:io';
import 'dart:typed_data';
//import 'dart:ui';
//import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' show join;
import 'crud_exceptions.dart';
import 'package:quiver/core.dart';
class MainService {
Database? _db; // stores database
List<DatabaseRouteMap> _maps = []; //stores list of maps
List<DatabaseNodesWeights> _weights = []; //stores list of weights
List<DatabaseRoutePointsInBetween> _pointsInBetween =
[]; //stores list of pointsInBetween
List<DatabaseNodes> _nodes = []; //stores list of nodes
//List<DatabaseUser> _user = []; //stores list of maps
//creates a stream of a list of DtabaseRouteMap which would keep track of the changes in _maps in this case
final _mapsStreamController =
StreamController<List<DatabaseRouteMap>>.broadcast();
final _weightsStreamController =
StreamController<List<DatabaseNodesWeights>>.broadcast();
final _pointsInBetweenStreamController =
StreamController<List<DatabaseRoutePointsInBetween>>.broadcast();
final _nodesStreamController =
StreamController<List<DatabaseNodes>>.broadcast();
//final _userStreamController =
// StreamController<List<DatabaseUser>>.broadcast();
Stream<List<DatabaseRouteMap>> get allMaps => _mapsStreamController.stream;
Stream<List<DatabaseNodes>> get allNodes => _nodesStreamController.stream;
//make mainservice a singleton
static final MainService _shared = MainService._sharedInstance();
MainService._sharedInstance();
factory MainService() => _shared;
//get all the nodes
Future<Iterable<DatabaseNodesWeights>> getAllNodesWeights() async {
await _ensureDbIsOpen();
final db = _getDatabaseOrThrow();
final nodesWeight = await db.query(nodesWeightsTable);
return nodesWeight
.map((nodeWeightRow) => DatabaseNodesWeights.fromRow(nodeWeightRow));
}
//gets user from an email inserted
Future<List<DatabaseNodesWeights>> getNodesWeightsUseNode(
{required String theNodesName, required int theNodesWeightId}) async {
await _ensureDbIsOpen();
final db = _getDatabaseOrThrow(); //locate database and store it
final results = await db.query(
nodesWeightsTable, //choose nodes table
where: 'node_1 = ?', // we are looking for x and y
whereArgs: [
theNodesName,
], //the x and y we are looking for has the same content as our argument
);
//if no results were returned throw an exception or return the node we are looking for
//in the list created above
if (results.isNotEmpty) {
late List<DatabaseNodesWeights> weights = [];
for (int i = 0; i < results.length; ++i) {
weights[i] = DatabaseNodesWeights.fromRow(results[i]);
//remove existing map from stream with the same identity of our updated value
_weights.removeWhere((weights) =>
weights.id ==
theNodesWeightId); //////////////Not 100% correct//////////////////////
//after removing the old value we insert the new value into the local list cache and the stream
//NOTE: in this case we are only updating the stream so the value is not affected, rather it is like we are getting updates of its status
_weights.add(weights[i]);
_weightsStreamController.add(_weights);
}
return weights;
} else {
throw CouldNotFindNodesWeight();
}
}
//get all the nodes
Future<Iterable<DatabaseNodes>> getAllNodes() async {
await _ensureDbIsOpen();
final db = _getDatabaseOrThrow();
final nodes = await db.query(nodesTable);
return nodes.map((nodeRow) => DatabaseNodes.fromRow(nodeRow));
}
class DatabaseNodes {
//variables
final int id;
final int x;
final int y;
final int isSelectable;
final String nodeName;
//constructor
DatabaseNodes({
required this.id,
required this.x,
required this.y,
required this.isSelectable,
required this.nodeName,
});
DatabaseNodes.fromRow(Map<String, Object?> map)
: id = map[nodesIdColumn] as int,
x = map[xColumn] as int,
y = map[yColumn] as int,
isSelectable = map[isSelectableColumn] as int,
nodeName = map[nodeNameColumn] as String;
@override
String toString() =>
'Nodes , ID = $id, x-coordinate = $x, y-coordinate = $y, Is it selectable = $isSelectable, node name = $nodeName';
@override
bool operator ==(covariant DatabaseUser other) => id == other.id;
@override
int get hashCode => id.hashCode;
}
class DatabaseNodesWeights {
//variables
final int id;
final String node_1;
final String node_2;
final int weight;
final int weightClass;
//constructor
DatabaseNodesWeights({
required this.id,
required this.node_1,
required this.node_2,
required this.weight,
required this.weightClass,
});
DatabaseNodesWeights.fromRow(Map<String, Object?> map)
: id = map[weightsIdColumn] as int,
node_1 = map[xColumn] as String,
node_2 = map[yColumn] as String,
weight = map[weightColumn] as int,
weightClass = map[weightClassWeightsColumn] as int;
@override
String toString() =>
'Nodes , ID = $id, starting node = $node_1, ending node = $node_2, weight =$weight';
@override
bool operator ==(covariant DatabaseUser other) => id == other.id;
@override
int get hashCode => id.hashCode;
}
const dbName = 'legsfree.db';
const userTable = 'user';
const nodesTable = 'nodes';
const routeMapTable = 'route_map';
const nodesWeightsTable = 'weights';
const routePointsInBetweenTable = 'route_points';
const userIdColumn = 'user_id';
const emailColumn = 'email';
const nodesIdColumn = 'node_id';
const xColumn = 'x';
const yColumn = 'y';
const isSelectableColumn = 'isSelectable';
const nodeNameColumn = 'node_name';
const routeMapIdColumn = 'route_map_id';
const mapFileNameColumn = 'map_name';
const mapsColumn = 'maps';
const location1RouteMapColumn = 'location_1';
const location2RouteMapColumn = 'location_2';
const totalWeightColumn = 'total_weight';
const journeyNameColumn = 'journey_name';
const weightClassMapsColumn = 'weight_class';
const isKnownColumn = 'isKnown';
const weightsIdColumn = 'weights_Id';
const node1Column = 'node_1';
const node2Column = 'node_2';
const weightColumn = 'weight';
const weightClassWeightsColumn = 'weight_class';
const routePointsIdColumn = 'route_points_id';
const location1RoutePointsColumn = 'location_1';
const location2RoutePointsColumn = 'location_2';
const pointsInBetweenColumn = 'points';
const routeIdColumn = 'route_id';
const positionColumn = 'position';
const createUserTable = '''CREATE TABLE IF NOT EXISTS "user" (
"user_id" INTEGER NOT NULL,
"email" TEXT NOT NULL UNIQUE,
PRIMARY KEY("user_id" AUTOINCREMENT)
);''';
const createNodesTable = '''CREATE TABLE IF NOT EXISTS "nodes" (
"node_id" INTEGER NOT NULL,
"x" INTEGER NOT NULL,
"y" INTEGER NOT NULL,
"isSelectable" INTEGER NOT NULL,
"node_name" TEXT NOT NULL,
PRIMARY KEY("node_id" AUTOINCREMENT)
);''';
const createRouteMapsTable = '''CREATE TABLE IF NOT EXISTS "route_map" (
"route_map_id" INTEGER NOT NULL,
"maps" BLOB NOT NULL,
"total_weight" INTEGER NOT NULL,
"location_1" INTEGER NOT NULL,
"location_2" INTEGER NOT NULL,
"map_name" TEXT NOT NULL,
"journey_name" TEXT NOT NULL,
"weight_class" INTEGER NOT NULL,
"isKnown" INTEGER NOT NULL,
PRIMARY KEY("route_map_id" AUTOINCREMENT)
);''';
const createWeightsTable = '''CREATE TABLE IF NOT EXISTS "weights" (
"node_1" TEXT NOT NULL,
"node_2" TEXT NOT NULL,
"weight" INTEGER NOT NULL,
"weights_id" INTEGER NOT NULL,
"weight_class" INTEGER NOT NULL,
PRIMARY KEY("weights_id" AUTOINCREMENT)
);''';
const createRoutePointsInBetweenTable =
'''CREATE TABLE IF NOT EXISTS "route_points" (
"route_points_id" INTEGER NOT NULL,
"location_1" INTEGER NOT NULL,
"location_2" INTEGER NOT NULL,
"points" INTEGER NOT NULL,
"route_id" INTEGER NOT NULL,
"position" INTEGER NOT NULL,
PRIMARY KEY("route_points_id" AUTOINCREMENT),
FOREIGN KEY("route_id") REFERENCES "route_map"("route_map_id")
);''';
https://github.com/eeyla2/Final_year_projectt 这是一个 github 链接,以防不清楚。
您最需要的文件是 https://github.com/eeyla2/Final_year_projectt/blob/main/lib/views/maps/new_maps_view.dart 和 https://github.com/eeyla2/Final_year_projectt /blob/main/lib/services/crud/main_services.dart