Use variable in widget build in flutter

I started programming in flutter, but I can’t pass a variable to a new class. I was able to do that on my other codes. Now I don’t know what to do.

import 'dart:io';
import 'package:camera/camera.dart';
import 'package:google_ml_kit/google_ml_kit.dart';
import 'package:flutter/material.dart';

class BilgiEkrani extends StatefulWidget {
  final String sonuc;
  final double oran;
  const BilgiEkrani({required this.sonuc, required this.oran});
  @override
  _BilgiEkrani createState() => _BilgiEkrani(sonuc, oran);
}

class _BilgiEkrani extends State<BilgiEkrani> {
  _BilgiEkrani(String sonuc, double oran);

  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
      toolbarHeight: 20,
      backgroundColor: Colors.pinkAccent,
      title: **sonuc**,
//Undefined name 'sonuc'.
//Try correcting the name to one that is defined, or defining the name.
    ));
  }
}

>Solution :

While you like to use variables inside State class that is coming from main class that extends StatefulWidget, you need to use widget.variableName. In your case, to use sonuc String inside state, you need to use widget.sonuc.

title: takes a widget, therefor you need to wrap sonic with widget then pass it there. For String, simply use Text widget.

title: Text(widget.sonuc),

You can learn more about widgets

Leave a Reply