在我的flutter应用程序中单击时更改容器的颜色 [英] Change the color of the container when clicked on it in my flutter app

查看:145
本文介绍了在我的flutter应用程序中单击时更改容器的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过API获取了一些兴趣(数据),并使用将来的构建器作为容器来展示它们.我想在单击容器时更改其背景颜色.这就是我所做的,并且当我单击一个容器时,它正在更改所有容器的背景颜色.

I fetched some interest(data) through an API and show them using future builders as containers. I want to change the background color of the container when I clicked on it. Here is what I did and it's changing the background color of all the containers when I clicked on one.

我在容器的颜色中添加了if条件,以检查是否被单击

I added an if condition to the color of the container to check whether it is clicked or not

颜色:isClicked? Colors.white:Color(0xFFFFEBE7),

color: isClicked? Colors.white : Color(0xFFFFEBE7),

,然后在单击时将isClicked状态设置为true.

and set the isClicked state to true when clicked.

bool isClicked = false;

FutureBuilder(
                      future: GetInterests.getInterests(),
                      builder: (context, snapshot) {
                        final datalist = snapshot.data;
                        if (snapshot.connectionState ==
                            ConnectionState.done) {
                          return Expanded(
                            child: SizedBox(
                              height: 35,
                              child: ListView.builder(
                                scrollDirection: Axis.horizontal,
                                itemBuilder: (context, index) {
                                  return Wrap(
                                    direction: Axis.vertical,
                                    children: <Widget>[
                                      GestureDetector(
                                        onTap: (){
                                          final inte_id =  "${datalist[index]['_id']}";
                                          log(inte_id);
                                          
                                          setState(() {
                                            isClicked = true;
                                          });
                                        },
                                        child: new Container(
                                          margin: EdgeInsets.only(right: 7),
                                          height: 30,
                                          width: MediaQuery.of(context)
                                                  .size
                                                  .width /
                                              5.2,
                                          decoration: BoxDecoration(
                                              color: isClicked? Colors.white : Color(0xFFFFEBE7),
                                              border: Border.all(
                                                  color: Color(0xFFE0E0E0)),
                                              borderRadius:
                                                  BorderRadius.only(
                                                      topLeft:
                                                          Radius.circular(
                                                              50.0),
                                                      topRight:
                                                          Radius.circular(
                                                              50.0),
                                                      bottomRight:
                                                          Radius.circular(
                                                              50.0),
                                                      bottomLeft:
                                                          Radius.circular(
                                                              0.0))),
                                          child: Center(
                                            child: Text(
                                              "${datalist[index]['iname']}",
                                              style: TextStyle(
                                                  fontFamily: 'Montserrat',
                                                  color: Color(0xFFFF5E3A),
                                                  fontSize: 13),
                                            ),
                                          ),
                                        ),
                                      ),
                                    ],
                                  );
                                },
                                itemCount: datalist.length,
                              ),
                            ),
                          );
                        }
                        return Padding(
                          padding: const EdgeInsets.only(left: 140.0),
                          child: Center(
                            child: CircularProgressIndicator(),
                          ),
                        );
                      },
                    )

我能够在控制台上打印感兴趣的ID,该ID属于我单击的容器.但不知道如何只改变颜色

I was able to print the interest id in the console which belongs to the container I clicked on. but don't know how to change its color only

推荐答案

在某些人看来,虽然可接受的答案将起作用,但使用ChangeNotifier和程序包提供程序的更为复杂的体系结构将产生更松散耦合的更好的代码.

While the accepted answer will work, a much more sophisticated architecture using ChangeNotifier and package provider will produce more loosely coupled, better code, in some folks opinion.

结合以下内容的想法

  • https://flutter.dev/docs/cookbook/networking/fetch-data
  • https://flutter.dev/docs/development/data-and-backend/state-mgmt/simple

我专注于体系结构和数据流.不在小部件布局上以匹配原始问题的屏幕截图.

I was focused on architecture and data flow. Not on widget layout to match the original question's screenshot.

import 'dart:collection';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:provider/provider.dart';

// Model ---------------------------------------------------

class Interest with ChangeNotifier {
  final String title;
  bool _selected = false;

  Interest({
    @required this.title,
  }) : assert(title != null);

  factory Interest.fromMap(final Map<String, dynamic> map) {
    return Interest(
      title: map['title'],
    );
  }

  bool get selected {
    return this._selected;
  }

  void select() {
    this._selected = true;
    this.notifyListeners();
  }

  void toggleSelect() {
    this._selected = !this._selected;
    this.notifyListeners();
  }
}

class Interests extends ChangeNotifier {
  final List<Interest> _interests = <Interest>[];

  Interests();

  factory Interests.fromList(final List<Map<String, dynamic>> list) {
    final Interests interests = Interests();
    for (final Map<String, dynamic> map in list) {
      interests.add(Interest.fromMap(map));
    }
    return interests;
  }

  int get length {
    return this._interests.length;
  }

  Interest operator [](final int index) {
    return this._interests[index];
  }

  UnmodifiableListView<Interest> get interests {
    return UnmodifiableListView<Interest>(this._interests);
  }

  void add(final Interest interest) {
    this._interests.add(interest);
    this.notifyListeners();
  }

  void selectAll() {
    for (final Interest interest in this._interests) {
      interest.select();
    }
  }
}

// Services ------------------------------------------------

Future<Interests> fetchInterests() async {
  // Some data source that has a list of objects with titles.
  final response = await http.get('https://jsonplaceholder.typicode.com/posts');
  if (response.statusCode == 200) {
    return Interests.fromList(json.decode(response.body).cast<Map<String, dynamic>>());
  } else {
    throw Exception('Failed to load post');
  }
}

// User Interface ------------------------------------------

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

class InterestsApp extends StatelessWidget {
  @override
  Widget build(final BuildContext context) {
    return MaterialApp(
      title: 'Interests App',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: InterestsPage(),
    );
  }
}

class InterestsPage extends StatelessWidget {
  @override
  Widget build(final BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Interests')),
      body: InterestsBody(),
    );
  }
}

class InterestsBody extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _InterestsBodyState();
  }
}

class _InterestsBodyState extends State<InterestsBody> {
  Future<Interests> _futureInterests;

  @override
  void initState() {
    super.initState();
    this._futureInterests = fetchInterests();
  }

  @override
  Widget build(final BuildContext context) {
    return FutureBuilder<Interests>(
      future: this._futureInterests,
      builder: (final BuildContext context, final AsyncSnapshot<Interests> snapshot) {
        if (snapshot.hasData) {
          return ChangeNotifierProvider.value(
            value: snapshot.data,
            child: InterestsList(),
          );
        } else if (snapshot.hasError) {
          return Center(child: Text("${snapshot.error}"));
        }
        return Center(child: CircularProgressIndicator());
      },
    );
  }
}

class InterestsList extends StatelessWidget {
  @override
  Widget build(final BuildContext context) {
    return Consumer<Interests>(
      builder: (final BuildContext context, final Interests interests, final Widget child) {
        return Column(
          children: <Widget>[
            Center(
              child: RaisedButton(
                child: Text("Select All"),
                onPressed: () {
                  interests.selectAll();
                },
              ),
            ),
            Expanded(
              child: ListView.builder(
                itemCount: interests.length,
                itemBuilder: (final BuildContext context, final int index) {
                  return ChangeNotifierProvider<Interest>.value(
                    value: interests[index],
                    child: InterestTile(),
                  );
                },
              ),
            ),
          ],
        );
      },
    );
  }
}

class InterestTile extends StatelessWidget {
  @override
  Widget build(final BuildContext context) {
    return Consumer<Interest>(
      builder: (final BuildContext context, final Interest interest, final Widget child) {
        return ListTile(
          title: Text(interest.title),
          trailing: interest.selected ? Icon(Icons.check) : null,
          onTap: () {
            interest.toggleSelect();
          },
        );
      },
    );
  }
}

这篇关于在我的flutter应用程序中单击时更改容器的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆