激活和停用Flutter中的收藏夹图标

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

我有这段代码。它包括带有国家/地区名称的图块列表,还包括“收藏夹”图标。我希望收藏夹图标在单击时激活和停用。请检查此代码,并告诉我代码有什么问题或更正代码。

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

void main() => runApp(
      MyApp(),
    );

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text("Favorite Item"),
        ),
        body: FavoriteItem(),
      ),
    );
  }
}

class FavoriteItem extends StatefulWidget {
  @override
  _FavoriteItemState createState() => _FavoriteItemState();
}

class _FavoriteItemState extends State<FavoriteItem> {
  @override
  Widget build(BuildContext context) {

     List<bool> _isFavorited = [];

    List<String> countryList = [
      'India',
      'America',
      'Australia',
      'Russia',
      'Japan',
      'China',
      'Nepal',
    ];
    return Center(
      child: ListView.builder(
        itemCount: countryList.length,
        itemBuilder: (context, index) {
          return ListTile(
            title: Text(
              countryList[index],
            ),
            trailing: IconButton(
              onPressed: () => setState(
                        () => _isFavorited[index] = !_isFavorited[index]),
                    icon: _isFavorited[index]
                        ? Icon(Icons.favorite)
                        : Icon(Icons.favorite_border),
            ),
          );
        },
      ),
    );
  }
}
flutter favorites
1个回答
0
投票

您需要初始化“ _isFavorited”。

class _FavoriteItemState extends State<FavoriteItem> {

// fix start.
  static final List<String> countryList = [
    'India',
    'America',
    'Australia',
    'Russia',
    'Japan',
    'China',
    'Nepal',
  ];
  List<bool> _isFavorited = List.filled(countryList.length, false);
// fix end.

  @override
  Widget build(BuildContext context) {
    return Center(
      child: ListView.builder(
        itemCount: countryList.length,
        itemBuilder: (context, index) {
          return ListTile(
            title: Text(
              countryList[index],
            ),
            trailing: IconButton(
              onPressed: () =>
                  setState(() => _isFavorited[index] = !_isFavorited[index]),
              icon: _isFavorited[index]
                  ? Icon(Icons.favorite)
                  : Icon(Icons.favorite_border),
            ),
          );
        },
      ),
    );
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.