0

Into the circleAvatar from flutter before user put they own image I want to replace the space with the Initial value the first digit of the currentUser variable name into TextWidget. it means for example the Name is "john" I want to get "J" how we can reach that?

  
  final imageUrl = true;

and build method

imageUrl ? CircleAvatar(
                radius: 60,
                backgroundImage: AssetImage(currentUser.imageUrl),)
                  : CircleAvatar(backgroundColor: Colors.yellow,
                child: Text(currentUser.name[0]),),
              SizedBox(
                height: 60,
              ),

In this way I get it but I dont know how to if imageUrl is null return currentUser.name[0]

2
  • please provide more information or code Commented Nov 7, 2020 at 15:32
  • I have edited the question I want to get the first digit of the text variable, if the name is John I want to get J Commented Nov 7, 2020 at 15:34

1 Answer 1

1

to get the first character of a name:

final s = "John";
print(s[0]); // => J

to guard against null, you can use the ?? or the ? operator.

to get a circle avatar with a character text widget as child instead of an image, depending on whether imageUrl is null or not:

imageUrl ? CircleAvatar(backgroundImage: NetworkImage(imageUrl),)
 : CircleAvatar(backgroundColor: Colors.brown.shade800,
    child: Text(currentUser && currentUser.isNotEmpty? currentUser[0] : "default"),)
Sign up to request clarification or add additional context in comments.

4 Comments

I meant initialValue of the Text Variable for example the first digit on the name.
to get the first character of a string variable s just use s[0], provided you know s is not empty
i added: bool imageUrl = false; final s = "${currentUser.name}"; and the code: imageUrl ? CircleAvatar( radius: 60, backgroundImage: AssetImage(currentUser.imageUrl),) : CircleAvatar(backgroundColor: Colors.yellow, child: Text( currentUser.name.isEmpty && currentUser.name.isNotEmpty? s[0] : "default"),), Image on circeavatar showing corrently but if I remove image the Initial value of the variable currentUser.name is not showing. I added the code above
imageUrl does not need to be a bool. a String (url) will also do. when imageUrl is null, it will be treated like false would. Your edited question is still confusing though. You can either use the code in a method returning a String or in a method returning a Widget (a build method f.e.). A method returning once a Widget and once a String is not rly helpful. In either case, you might wanna use if and else instead of ? and :, if this is confusing for you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.