Flutter: ожидаемое значение ошибки типа. Проходя в String, Widget ожидает что-то другое - PullRequest
0 голосов
/ 23 апреля 2020

Я передаю имя объект в виде STRING в виджет без состояния для определения функций logi c. При передаче в строке я получаю сообщение об ошибке Ожидаемое значение типа ' WIDGETNAME ', но получаю одно из типа 'String'.

Как изменить виджет без сохранения состояния для получения строки?

WIDGET

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:oblio_app/ui/theme/colors.dart';
import 'package:oblio_app/ui/widgets/list_builders/list_builder_attribution.dart';

class NestedTabsAttributionCard extends StatefulWidget {
  @override
  _NestedTabsAttributionCardState createState() =>
      _NestedTabsAttributionCardState();
}

class _NestedTabsAttributionCardState extends State<NestedTabsAttributionCard>
    with TickerProviderStateMixin {
  TabController _nestedTabController;

  @override
  void initState() {
    super.initState();

    _nestedTabController = new TabController(length: 3, vsync: this);
  }

  @override
  void dispose() {
    super.dispose();
    _nestedTabController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    //  double screenHeight = MediaQuery.of(context).size.height;
    return Column(
      mainAxisAlignment: MainAxisAlignment.spaceAround,
      children: <Widget>[
        Container(
          alignment: Alignment.centerLeft,
          margin: EdgeInsets.fromLTRB(0, 0, 0, 00),
          child: TabBar(
            controller: _nestedTabController,
            indicatorColor: CompanyColors.indigo[400],
            labelColor: CompanyColors.indigo[400],
            unselectedLabelColor: CompanyColors.font_primary[60],
            isScrollable: false,
            tabs: <Widget>[
              Tab(
                text: "Campaign",
              ),
              Tab(
                text: "Persona",
              ),
              Tab(
                text: "Creative",
              ),
            ],
          ),
        ),
        Flexible(
          flex: 1,
          child: Container(
            //   height: screenHeight * 1.00,
            alignment: Alignment.center,
            child: TabBarView(
              controller: _nestedTabController,
              children: <Widget>[
                ListBuilderAttribution(name: 'Campaign'),
                ListBuilderAttribution(name: 'Persona'),
                ListBuilderAttribution(name: 'Creative'),
              ],
            ),
          ),
        )
      ],
    );
  }
}

LISTBUILD WIDGET

import 'package:flutter/material.dart';
import 'package:oblio_app/ui/layouts/list_tiles/columns/attribution/attribution.dart';
import 'package:oblio_app/ui/theme/colors.dart';
import 'package:oblio_app/ui/widgets/dividers/attribution_vertical_divider.dart';

class ListBuilderAttribution extends StatefulWidget {
  ListBuilderAttribution({
    Key key,
    this.name,
  }) : super(key: key);

  final String name;

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

class _ListBuilderAttributionState extends State<ListBuilderAttribution> {
  List<LayoutListTileColumnAttribution> attribution = [
    LayoutListTileColumnAttribution(
      progress: '30',
      field1: 'Goal',
      field2: 'Persona',
      field3: 'UseCase',
      field4: 'AdGroup',
    ),
    LayoutListTileColumnAttribution(
      progress: '20',
      field1: 'Goal',
      field2: 'Persona',
      field3: 'UseCase',
      field4: 'AdGroup',
    ),
    LayoutListTileColumnAttribution(
      progress: '10',
      field1: 'Goal',
      field2: 'Persona',
      field3: 'UseCase',
      field4: 'Ad Group',
    ),
  ];

  var label1;
  var label2;
  var label3;
  var label4;

  var ringColor;

  @override
  void initState() {
    super.initState();
    if (widget.name == 'Campaign') {
      label1 = 'Goal';
      label2 = 'Persona';
      label3 = 'Use Case';
      label4 = 'Ad Group';
    } else if (widget.name == 'Persona') {
      label1 = 'Goal';
      label2 = 'Persona';
      label3 = 'Use Case';
      label4 = 'Ad Group';
    } else if (widget.name == 'Creative') {
      label1 = 'Goal';
      label2 = 'Persona';
      label3 = 'Use Case';
      label4 = 'Ad Group';
    } else {
      label1 = 'Error';
      label2 = 'Error';
      label3 = 'Error ';
      label4 = 'Error';
    }
    if (attribution.indexOf(label1) == 0) {
      ringColor = CompanyColors.indigo[500];
    } else if (attribution.indexOf(label1) == 1) {
      ringColor = CompanyColors.orange[500];
    } else if (attribution.indexOf(label1) == 2) {
      ringColor = CompanyColors.red[500];
    } else if (attribution.indexOf(label1) == 3) {
      ringColor = CompanyColors.green[500];
    } else {
      ringColor = CompanyColors.red[900];
    }
  }

  @override
  Widget build(BuildContext context) {
    return ListView.separated(
        separatorBuilder: (context, index) => AttributionDivider(),
        scrollDirection: Axis.horizontal,
        shrinkWrap: true,
        itemCount: 3,
        itemBuilder: (context, index) {
          return LayoutListTileColumnAttribution(
            ringColor: ringColor,
            progress: attribution[index].progress,
            label1: label1,
            field1: attribution[index].field1,
            label2: label2,
            field2: attribution[index].field2,
            label3: label3,
            field3: attribution[index].field3,
            label4: label4,
            field4: attribution[index].field4,
          );
        });
  }
}

Следующий объект TypeErrorImpl был брошен при создании KeyedSubtree - [<0>]: ожидаемое значение типа 'LayoutListTileColumnAttribution', но получил один из типов 'String'. Соответствующий виджет, вызывающий ошибки, был: Файл TabBarView: ///Users/timothysolomon/Development/apps/oblio_app/oblio_app/lib/ui/widgets/tabs/attribution_card/nested_tabs_attribution_card.dart: 65 20 Когда возникло исключение, это был стек: dart-sdk / lib / _internal / js_dev_runtime / private / ddc_runtime / errors.dart 195: 49 throw_ dart-sdk / lib / _internal / js_dev_runtime / private / ddc_runtime / errors.dart 44: 3 castError dart-sdk / lib / _internal / js_dev_runtime / private / ddc_runtime / operations.dart 406: 10 приведение dart-sdk / lib / _internal / js_dev_runtime / private / ddc_runtime / classes.dart 541: 1 4 пакета as_C / oblio_app / ui / widgets / list_builders / list_builder_attribution.dart 74:37 initState ...

Ответы [ 2 ]

2 голосов
/ 23 апреля 2020

Проблема определенно в следующей строке.

if (attribution.indexOf(label1) == 0)

Здесь вы пытаетесь найти (сравнить) label1 в атрибуции, которая является списком типов LayoutListTileColumnAttribution, поэтому для сравнения вы должны передать объект типа LayoutListTileColumnAttribution в indexOf.

Для сравнения объекта класса вы должны переопределить метод =, а также hashmap, но лучше выбрать go с пакетом equatable , поэтому вам не нужно создавать множество шаблонов code.

Наконец, здесь возникает актуальная проблема.

Здесь вы хотите сравнить строку с переменной объекта, которая невозможна напрямую.

Я думаю, что вы должны использовать перебираем весь список и сравниваем с label1.

 int findindex = -1;
  int i;

for (i = 0; i < attribution.length; i++) {
      if (attribution[i].field1 == label1) {
        findindex = i;
        break;
      }
    }
    if (findindex == 0) {
      ringColor = CompanyColors.indigo[500];
    } else if (findindex == 1) {
      ringColor = CompanyColors.orange[500];
    } else if (findindex == 2) {
      ringColor = CompanyColors.red[500];
    } else if (findindex == 3) {
      ringColor = CompanyColors.green[500];
    } else {
      ringColor = CompanyColors.red[900];
    }
0 голосов
/ 23 апреля 2020

Супер просто!

Создайте метод в построителе списков для getRingColor

   Color getRingColor(int index) {
    return [
      CompanyColors.indigo[400],
      CompanyColors.orange[400],
      CompanyColors.red[400]
    ][index];
  }

  @override
  Widget build(BuildContext context) {
    return ListView.separated(
        separatorBuilder: (context, index) => AttributionDivider(),
        scrollDirection: Axis.horizontal,
        shrinkWrap: true,
        itemCount: 3,
        itemBuilder: (context, index) {
          return LayoutListTileColumnAttribution(
            ringColor: getRingColor(index),
            progress: attribution[index].progress,
            label1: label1,
            field1: attribution[index].field1,
            label2: label2,
            field2: attribution[index].field2,
            label3: label3,
            field3: attribution[index].field3,
            label4: label4,
            field4: attribution[index].field4,
          );
        });
  }
}
...