Search code examples
flutterclassdartcolorscontainers

Dart, flutter - The argument type 'String' can't be assigned to the parameter type 'Color?'


Im trying to assign a container color to a class property from a models file in dart. However it gave me an error that The argument type 'String' can't be assigned to the parameter type 'Color?'.

Here is my models file

Driver(
  name: 'Max Verstappen',
  rank: '1',
  team: 'Red Bull Racing',
  points: '182',
  color: 'Colors.blue[800]',
)

And here is the container widget

Padding(
 padding: EdgeInsets.only(left: 15),
 child: Container(
   width: 4,
   height: 50,
   color: driver.color,
 ),
),

Error

The argument type 'String' can't be assigned to the parameter type 'Color?

Solution

  • The type of a color is Color.

    import 'dart:ui';
    
    class Driver {
      final String name;
      final String rank;
      final String team;
      final String points;
      final Color? color;
    
      Driver({this.name, this.rank, this.team, this.points, this.color});
    }
    

    when you call it, remember to import material package on the top of your dart file to get the Colors class.

    import 'package:flutter/material.dart';
    
    final driver = Driver(
      name: 'Max Verstappen',
      rank: '1',
      team: 'Red Bull Racing',
      points: '182',
      color: Colors.blue[800],
    );