programing

'List' 유형은 'List' 유형의 하위 유형이 아닙니다.

css3 2023. 6. 14. 22:06

'List' 유형은 'List' 유형의 하위 유형이 아닙니다.

Firestore에서 복사한 코드 조각이 있습니다. 예:

Widget _buildBody(BuildContext context) {
    return new StreamBuilder(
      stream: _getEventStream(),
      builder: (context, snapshot) {
        if (!snapshot.hasData) return new Text('Loading...');
        return new ListView(
          children: snapshot.data.documents.map((document) {
            return new ListTile(
              title: new Text(document['name']),
              subtitle: new Text("Class"),
            );
          }).toList(),
        );
      },
    );
  }

하지만 이 오류가 발생합니다.

type 'List<dynamic>' is not a subtype of type 'List<Widget>'

여기서 뭐가 잘못됐습니까?

여기서 문제는 유형 추론이 예상치 못한 방식으로 실패한다는 것입니다.해결책은 다음에 형식 인수를 제공하는 것입니다.map방법.

snapshot.data.documents.map<Widget>((document) {
  return new ListTile(
    title: new Text(document['name']),
    subtitle: new Text("Class"),
  );
}).toList()

더 복잡한 대답은 유형이children이라List<Widget>그 정보는 다시 흘러가지 않습니다.map호출왜냐하면.map다음은toList폐쇄 반환에 주석을 달 방법이 없기 때문입니다.

제 앱에서 읽으려고 했던 파이어스토어의 문자열 목록이 있었습니다.List of String에 캐스트를 하려고 했을 때 동일한 오류가 발생했습니다.

type 'List<dynamic>' is not a subtype of type 'List<Widget>'

이 해결책은 저에게 도움이 되었습니다.이것을 확인해 보세요.

var array = document['array']; // array is now List<dynamic>
List<String> strings = List<String>.from(array);

동적 리스트를 특정 유형으로 리스트에 캐스트할 수 있습니다.

List<'YourModel'>.from(_list.where((i) => i.flag == true));

변환을 통해 문제를 해결했습니다.Map로.Widget

children: snapshot.map<Widget>((data) => 
    _buildListItem(context, data)).toList(),

일부 위젯의 자식 속성에서 _buildBody를 사용하므로 아이들은 목록 위젯(위젯 배열)을 기대하고 _buildBody는 '목록 동적'을 반환합니다.

매우 간단한 방법으로 변수를 사용하여 반환할 수 있습니다.

// you can build your List of Widget's like you need
List<Widget> widgets = [
  Text('Line 1'),
  Text('Line 2'),
  Text('Line 3'),
];

// you can use it like this
Column(
  children: widgets
)

예(flutter create test1; cd test1; edit lib/main.dart; flutter run):

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  List<Widget> widgets = [
    Text('Line 1'),
    Text('Line 2'),
    Text('Line 3'),
  ];

  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text("List of Widgets Example")),
        body: Column(
          children: widgets
        )
      )
    );
  }

}

위젯 목록(위젯 배열) 내에서 위젯(하나의 위젯)을 사용하는 다른 예제입니다.위젯을 개인화하고 코드 크기를 줄이기 위해 위젯(MyButton)의 범위를 표시합니다.

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  List<Widget> arrayOfWidgets = [
    Text('My Buttons'),
    MyButton('Button 1'),
    MyButton('Button 2'),
    MyButton('Button 3'),
  ];

  Widget oneWidget(List<Widget> _lw) { return Column(children: _lw); }

  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text("Widget with a List of Widget's Example")),
        body: oneWidget(arrayOfWidgets)
      )
    );
  }

}

class MyButton extends StatelessWidget {
  final String text;

  MyButton(this.text);

  @override
  Widget build(BuildContext context) {
    return FlatButton(
      color: Colors.red,
      child: Text(text),
      onPressed: (){print("Pressed button '$text'.");},
    );
  }
}

동적 위젯을 사용하여 위젯을 화면에 표시하고 숨깁니다. 다트 피들에서도 온라인으로 실행되는 것을 볼 수 있습니다.

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  List item = [
    {"title": "Button One", "color": 50},
    {"title": "Button Two", "color": 100},
    {"title": "Button Three", "color": 200},
    {"title": "No show", "color": 0, "hide": '1'},
  ];

  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text("Dynamic Widget - List<Widget>"),backgroundColor: Colors.blue),
        body: Column(
          children: <Widget>[
            Center(child: buttonBar()),
            Text('Click the buttons to hide it'),
          ]
        )
      )
    );
  }

  Widget buttonBar() {
    return Column(
      children: item.where((e) => e['hide'] != '1').map<Widget>((document) {
        return new FlatButton(
          child: new Text(document['title']),
          color: Color.fromARGB(document['color'], 0, 100, 0),
          onPressed: () {
            setState(() {
              print("click on ${document['title']} lets hide it");
              final tile = item.firstWhere((e) => e['title'] == document['title']);
              tile['hide'] = '1';
            });
          },
        );
      }
    ).toList());
  }
}

누군가에게 도움이 될 수도 있습니다.도움이 되셨다면 위쪽 화살표를 클릭하여 알려주시기 바랍니다.감사해요.

https://httpspad.dev/b37b08cc25e0cdba680090e9ef4b3c1

나의 해결책은, 당신이 캐스팅할 수 있다는 것입니다.List<dynamic>안으로List<Widget>다음에 간단한 코드를 추가할 수 있습니다.snapshot.data.documents.map안으로snapshot.data.documents.map<Widget>제가 아래에 보여드릴 코드처럼.

이로부터

return new ListView(
          children: snapshot.data.documents.map((document) {
            return new ListTile(
              title: new Text(document['name']),
              subtitle: new Text("Class"),
            );
          }).toList(),
        );

이 안으로

return new ListView(
          children: snapshot.data.documents.map<Widget>((document) {
            return new ListTile(
              title: new Text(document['name']),
              subtitle: new Text("Class"),
            );
          }).toList(),
        );

이것은 나에게 효과가 있습니다.List<'YourModel'>.from(_list.where((i) => i.flag == true));

예:

List<dynamic> listOne = ['111','222']
List<String> ListTwo = listOne.cast<String>();

리스트 유형을 동적에서 문자열로 변경한 후 핫 새로고침을 수행하면 이 오류가 발생할 것으로 생각합니다. 핫 재시작이 해결책입니다.

기억하세요: 핫 재시작은 전체 클래스가 아닌 빌드() 함수만 재구축하고 클래스의 맨 위에 있는 목록이 빌드() 함수 밖에 있다고 선언합니다.

추가하여 목록으로 변경.toList()했습니다.

변화하는

List list = [];

대상:

List<Widget> list = [];

내 문제 해결!!

언급URL : https://stackoverflow.com/questions/49603021/type-listdynamic-is-not-a-subtype-of-type-listwidget