Search code examples
flutterdartflutter-gridview

How to edit specific items in GridView?


How would I edit / target specifics item in this GridView. This Gridview lays out the days of Jan 2020 in each container. How would I change the container's border of a specific date? Example... I want to change the border to red instead of black of the second item in the first row (01-02-2020)

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final title = 'Grid List';

    return MaterialApp(
      title: title,
      home: Scaffold(
        appBar: AppBar(
          title: Text(title),
        ),
        body: GridView.count(
          // Create a grid with 2 columns. If you change the scrollDirection to
          // horizontal, this produces 2 rows.
          crossAxisCount: 4,
          // Generate 100 widgets that display their index in the List.
          children: getDayInWeek(),
        ),
      ),
    );
  }
}

List<Widget> getDayInWeek() {
  var list = <DateTime>[];
  DateTime start = DateTime(2020, 01, 01);
  final end = DateTime(2020, 01, 31);

  while (start.isBefore(end)) {
    list.add(start);
    start = start.add(const Duration(days: 1));
  }

  return list.map((DateTime time) {
    return Container(
      margin: const EdgeInsets.all(2.0),
      padding: const EdgeInsets.all(.0),
      decoration: myBoxDecoration(),
      child: Column(
        children: <Widget>[
          Text(
            new DateFormat("MM-dd-yyyy").format(time),
            style: TextStyle(fontSize: 15.0, backgroundColor: Colors.white),
            textAlign: TextAlign.center,
          ),
        ],
      ),
    );
  }).toList();
}

BoxDecoration myBoxDecoration() {
  return BoxDecoration(
    border: Border.all(width: .1),
  );
}

Solution

  • you can use index and use ternary condition to change border colour in your BoxDecoration(). like i use in my app.

    Container(
         height: 30,
         width: 155,
         decoration: ShapeDecoration(
        shape: RoundedRectangleBorder(
        side: BorderSide(
        color: index == 7
        ? dateDifference
           ? Colors.red
           : lightGrey
           : lightGrey),
           borderRadius:
           BorderRadius.all(Radius.circular(3.0)),
         ),
      ),