列出未来字符串时出错,它显示“人”实例

问题描述 投票:0回答:1

我正在为自己制作一个 Flutter 网络应用程序,用于练习。 该应用程序从邮递员那里接收姓名,它为该姓名生成一个用户 ID,并存储它。 当用户在数据库中时,会弹出一个屏幕并显示他/她的 ID 以及列表中的用户。

现在弹出屏幕时,它显示了正确的行数,但没有显示用户名,而是:“Instance of Person”

代码如下:

mainscreen.dart

import 'package:flutter/material.dart';
import 'api.dart';
import 'person.dart';

class MainScreen extends StatefulWidget {
  const MainScreen({Key? key, required person}) : super(key: key);

  @override
  _MainScreenState createState() => _MainScreenState();
}

class _MainScreenState extends State<MainScreen> {
  TextEditingController _usernameController = TextEditingController();
  TextEditingController _passwordController = TextEditingController();

  Future<List<Person>> _futurePersons = Api.getPersons();

  void _login() async {
    String username = _usernameController.text;
    String password = _passwordController.text;

    try {
      final persons = await _futurePersons;

      final currentUserIndex = persons.indexWhere(
        (person) => person.name == username,
      );
      final currentUser =
          currentUserIndex > -1 ? persons[currentUserIndex] : null;

      if (currentUser != null) {
        showDialog(
          context: context,
          builder: (BuildContext context) => LayoutBuilder(
            builder: (_, constrains) => AlertDialog(
                title: Text('Szia, ${currentUser.name}'),
                scrollable: true,
                content: Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text('A te ID-d: ${currentUser.id}'),
                    SizedBox(height: 8),
                    Text('A felhasznalok:'),
                    Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        for (var person in persons)
                          Text(
                            person.toString(),
                            style: TextStyle(fontSize: 20),
                          )
                      ],
                    ),
                  ],
                )),
          ),
        );
      } else {
        showDialog(
          context: context,
          builder: (BuildContext context) => AlertDialog(
            title: Text('Hiba'),
            content: Text('Nincs ilyen nevu felhasznalo'),
          ),
        );
      }
    } catch (e) {
      print('Hiba a felhasznalo keresese kozben: $e');
      showDialog(
        context: context,
        builder: (BuildContext context) => AlertDialog(
          title: Text('Hiba'),
          content: Text('Nem sikerult megtalalni a felhasznalot'),
        ),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('teszt'),
      ),
      body: Padding(
        padding: EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            TextFormField(
              controller: _usernameController,
              decoration: InputDecoration(
                hintText: 'Felhasznalo nev',
              ),
            ),
            SizedBox(height: 16.0),
            TextFormField(
              controller: _passwordController,
              obscureText: true,
              decoration: InputDecoration(
                hintText: 'Jelszo',
              ),
            ),
            SizedBox(height: 16.0),
            ElevatedButton(
              onPressed: _login,
              child: Text('Belepes'),
            ),
          ],
        ),
      ),
    );
  }
}

api.dart

import 'dart:convert';
import 'package:http/http.dart' as http;
import 'person.dart';

class Api {
  static const endpoint = 'http://localhost:8080/api/v1/person';

  static Future<List<Person>> getPersons() async {
    final response = await http.get(Uri.parse(endpoint));
    if (response.statusCode == 200) {
      final Iterable data = json.decode(response.body);
      return List<Person>.from(data.map((person) => Person.fromJson(person)));
    } else {
      throw Exception('Nem sikerult felhasznalot hozzaadni!');
    }
  }

  static Future<Person> addPerson(Person person) async {
    final response = await http.post(
      Uri.parse(endpoint),
      headers: <String, String>{
        'Content-Type': 'application/json; charset=UTF-8',
      },
      body: jsonEncode(person.toJson()),
    );
    if (response.statusCode == 200) {
      final data = json.decode(response.body);
      return Person.fromJson(data);
    } else {
      throw Exception('Nem sikerult felhasznalot hozzaadni!');
    }
  }

  static Future<void> deletePerson(String id) async {
    final url = Uri.parse('$endpoint/$id');
    final response = await http.delete(url);
    if (response.statusCode != 204) {
      throw Exception('Nem sikerult felhasznalot torolni!');
    }
  }

  static Future<void> updatePerson(Person person) async {
    final url = Uri.parse('$endpoint/${person.id}');
    final response = await http.put(
      url,
      headers: <String, String>{
        'Content-Type': 'application/json; charset=UTF-8',
      },
      body: jsonEncode(person.toJson()),
    );
    if (response.statusCode != 204) {
      throw Exception('Nem sikerult felhasznalot update-lni!');
    }
  }
}

person.dart

import 'package:uuid/uuid.dart';

class Person {
  final String id;
  final String name;

  Person({
    required this.id,
    required this.name,
  });

  factory Person.fromJson(Map<String, dynamic> json) {
    return Person(
      id: json['id'] as String,
      name: json['name'] as String,
    );
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['name'] = this.name;
    return data;
  }

  factory Person.newPerson(String name) {
    return Person(
      id: Uuid().v4(),
      name: name,
    );
  }

  static Person getDefault() {
    return Person(id: "", name: "");
  }
}

我尝试了多种解决方案,但似乎没有任何效果。

flutter dart instance future
1个回答
0
投票

我想你忘了在 Person 类中定义 toString() 函数。只需在 Person 类中添加此功能:

String toString(){ return name;}
© www.soinside.com 2019 - 2024. All rights reserved.